//------------------------------------------------------------------------------
// <pcdd-entitiy>
//     彩票主流业务类库
//     会员业务对象
// </pcdd-entitiy>
//------------------------------------------------------------------------------ 

using CL.Enum.Common;
using CL.Game.DAL;
using CL.Game.Entity;
using CL.Json.Entity;
using CL.Json.Entity.WebAPI;
using CL.Redis.BLL;
using CL.Tools.Common;
using CL.View.Entity.Game;
using CL.View.Entity.Integrated;
using CL.View.Entity.Redis;
using System;
using System.Collections.Generic;
using CL.Entity.Json.WebAPI;
using CL.Enum.Common.Lottery;
using CL.Coupons.BLL;
using System.Threading.Tasks;
using CL.Enum.Common.Type;

namespace CL.Game.BLL
{

    /// <summary>
    /// UsersBLL 业务
    /// </summary>
    public class UsersBLL
    {
        Log log = new Log("UsersBLL");
        UsersDAL dal = new UsersDAL(DbConnectionEnum.CaileGame);

        /// <summary>
        /// 根据用户编号查询用户对象
        /// </summary>
        /// <param name="UserCode">用户编号</param>
        /// <returns></returns>
        public UsersEntity QueryEntityByUserCode(long UserCode)
        {
            return dal.QueryEntityByUserCode(UserCode);
        }
        /// <summary>
        /// 根据手机号码查询用户对象
        /// </summary>
        /// <param name="UserCode">用户编号</param>
        /// <returns></returns>
        public UsersEntity QueryEntityByUserMobile(string Mobile)
        {
            return dal.QueryEntityByUserMobile(Mobile);
        }
        /// <summary>
        /// 插入用户对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public long InsertEntity(UsersEntity entity)
        {
            return dal.InsertEntity(entity);
        }

        /// <summary>
        /// 修改对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int ModifyEntity(UsersEntity entity)
        {
            return dal.ModifyEntity(entity);
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string UserName)
        {
            return dal.Exists(UserName);
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(long UserID)
        {
            return dal.Exists(UserID);
        }
        /// <summary>
        /// 获取用户数据列表
        /// </summary>
        public List<udv_UserInfo> QueryListByPage(string UserName, string StartTime, string EndTime, int pageSize, int pageIndex, ref int recordCount)
        {
            return dal.QueryListByPage(UserName, StartTime, EndTime, pageSize, pageIndex, ref recordCount);
        }
        /// <summary>
        /// 后台手动充值
        /// </summary>
        /// <returns></returns>
        public long AddUserBalanceManual(int AdminID, string UserName, long Money, string Memo, ref string ReturnDescription)
        {
            long Rec = dal.AddUserBalanceManual(AdminID, UserName, Money, Memo, ref ReturnDescription);
            if (Rec > 0)
                Task.Factory.StartNew(() =>
                {
                    //变更静态数据
                    new UsersBLL().Staticdata_Recharge(false, Money);
                });
            return Rec;
        }
        /// <summary>
        /// 设置静态数据
        /// </summary>
        /// <param name="DateDay">当天日期</param>
        /// <param name="StaticdataType">静态数据类型 1今日充值总额 2今日线上充值 3今日线下充值 4今日提现总额 5今日新增会员 6今日赠送金额 7彩种投注 8彩种中奖</param>
        /// <param name="Amount">静态数据金额</param>
        /// <param name="UsersCount">新增用户</param>
        /// <param name="LotteryCode">彩种</param>
        /// <returns></returns>
        public bool SetSystemStaticdata(int StaticdataType, long Amount, int UsersCount = 0, int LotteryCode = 0)
        {
            return dal.SetSystemStaticdata(DateTime.Now.ToString("yyyy-MM-dd"), StaticdataType, Amount, UsersCount, LotteryCode);
        }

        /// <summary>
        /// 彩豆兑换
        /// </summary>
        /// <param name="UserCode"></param>
        /// <param name="Amount"></param>
        /// <param name="Bean"></param>
        /// <returns></returns>
        public int ExchangeCaileBean(long UserCode, long Amount, long Bean, ref long Balance, ref long Gold)
        {
            int Rec = dal.ExchangeCaileBean(UserCode, Amount, Bean);
            if (Rec == 0)
            {
                var Entity = new SystemRedis().SignInByUserCodeRedis(UserCode);
                if (Entity != null)
                {
                    Entity.Balance = Entity.Balance - Amount;
                    Entity.Gold = Entity.Gold + Bean;
                    Balance = Entity.Balance;
                    Gold = Entity.Gold;
                    new SystemRedis().SignInSessionRedis(Entity);
                }
            }
            return Rec;
        }

        public string GetUserID(string idCards)
        {
            return dal.GetUserID(idCards);
        }





        #region 自定义方法

        /// <summary>
        /// 更新redis用户余额
        /// </summary>
        /// <param name="UserCode"></param>
        /// <param name="Amount"></param>
        /// <param name="IsAdd"></param>
        /// <returns></returns>
        public bool ModifyUserBalanceRedis(long UserCode, long Amount, bool IsAdd)
        {
            try
            {
                var UsersRedisEntity = new SystemRedis().SignInByUserCodeRedis(UserCode);
                if (IsAdd)
                    UsersRedisEntity.Balance = UsersRedisEntity.Balance + Amount;
                else
                    UsersRedisEntity.Balance = UsersRedisEntity.Balance - Amount;
                new SystemRedis().ModifySignInSessionRedis(UsersRedisEntity);
                return true;
            }
            catch (Exception ex)
            {
                log.Write("更新Redis用户余额失败[ModifyUserBalanceRedis]：" + ex.StackTrace, true);
                return false;
            }
        }
        /// <summary>
        /// 中奖
        /// </summary>
        /// <param name="Amount"></param>
        /// <param name="LotteryCode"></param>
        public void Staticdata_Aaward(long Amount, int LotteryCode)
        {
            this.SetSystemStaticdata((int)StaticdataTypeEnum.LotWin, Amount, 0, LotteryCode);
        }
        /// <summary>
        /// 购彩
        /// </summary>
        /// <param name="Amount"></param>
        /// <param name="LotteryCode"></param>
        public void Staticdata_Buy(long Amount, int LotteryCode)
        {
            this.SetSystemStaticdata((int)StaticdataTypeEnum.LotBuy, Amount, 0, LotteryCode);
        }
        /// <summary>
        /// 新增会员
        /// </summary>
        /// <param name="UserCount"></param>
        public void Staticdata_AddUser(int UserCount)
        {
            this.SetSystemStaticdata((int)StaticdataTypeEnum.DayUsers, 0, UserCount);
        }
        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="IsOnline"></param>
        /// <param name=""></param>
        public void Staticdata_Recharge(bool IsOnline, long Amount)
        {
            if (IsOnline)
                this.SetSystemStaticdata((int)StaticdataTypeEnum.DayOnline, Amount);
            else
                this.SetSystemStaticdata((int)StaticdataTypeEnum.DayOffline, Amount);
            this.SetSystemStaticdata((int)StaticdataTypeEnum.DayRecharge, Amount);
        }
        /// <summary>
        /// 提现
        /// </summary>
        /// <param name="Amount"></param>
        public void Staticdata_Withdraw(long Amount)
        {
            this.SetSystemStaticdata((int)StaticdataTypeEnum.DayWithdraw, Amount);
        }
        /// <summary>
        /// 赠送
        /// </summary>
        /// <param name="Amount"></param>
        public void Staticdata_Largess(long Amount)
        {
            this.SetSystemStaticdata((int)StaticdataTypeEnum.DayLargess, Amount);
        }

        /// <summary>
        /// 微信unionid兼容openid
        /// </summary>
        /// <param name="UnionID"></param>
        /// <param name="OpenID"></param>
        public void WeChatCompatible(string UnionID, string OpenID)
        {
            try
            {
                var Entity = new SystemRedis().SignInByWechatTokenRedis(OpenID);
                if (Entity != null)
                {
                    new SystemRedis().RemoveWechatTokenRedis(OpenID);
                    UsersExtendEntity UsersExtend = new UsersExtendBLL().QueryEntityByUserCode(Entity.UserCode);
                    if (UsersExtend != null && UsersExtend.WechatID.Trim() == OpenID)
                    {
                        UsersExtend.WechatID = UnionID;
                        new UsersExtendBLL().ModifyEntity(UsersExtend);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Write("微信unionid兼容openid方法[WeChatCompatible]错误:" + ex.StackTrace, true);
            }
        }

        /// <summary>
        /// 查询登录信息
        /// </summary>
        /// <param name="UserCode"></param>
        /// <param name="Token"></param>
        /// <returns></returns>
        protected LoginData SetUserData(long UserCode, string Token)
        {
            LoginData userData = null;
            var Entity = new SystemRedis().SignInByUserCodeRedis(UserCode);
            if (!Entity.IsCanLogin) //如果redis屏蔽 则同步db是否允许登录
            {
                var UserEntity_DB = new UsersBLL().QueryEntityByUserCode(Entity.UserCode);
                if (UserEntity_DB != null && Entity.IsCanLogin != UserEntity_DB.IsCanLogin)
                {
                    Entity.IsCanLogin = UserEntity_DB.IsCanLogin;
                    new SystemRedis().SignInSessionRedis(Entity);
                }
            }
            if (Entity.IsCanLogin)
            {
                //判断是否实名认证 实名认证是否有真实姓名
                if (Entity.IsCertification && string.IsNullOrEmpty(Entity.FullName))
                {
                    var UsersExtendEntity = new UsersExtendBLL().QueryEntityByUserCode(Entity.UserCode);
                    Entity.FullName = UsersExtendEntity.FullName;
                    new SystemRedis().ModifySignInSessionRedis(Entity);//写入Redis
                }
                userData = new LoginData()
                {
                    VIP = Entity.VIP,
                    UserCode = Entity.UserCode,
                    AvatarUrl = Entity.AvatarUrl,
                    Balance = Entity.Balance,
                    Gold = Entity.Gold,
                    IsCertification = Entity.IsCertification,
                    IsRobot = Entity.IsRobot,
                    Level = Entity.Level,
                    Mobie = Entity.Mobie,
                    Nick = Entity.Nick,
                    SpecialGroup = Entity.SpecialGroup,
                    Token = Token,
                    FullName = Entity.FullName,
                    IsWithdrawPwd = string.IsNullOrEmpty(Entity.PayPwd) == true ? false : true,
                    Uid = DESEncrypt.Encrypt(Convert.ToString(Entity.UserCode))
                };
            }
            return userData;
        }
        /// <summary>
        /// 用户信息保存redis
        /// </summary>
        /// <param name="Entity"></param>
        /// <param name="ExtendEntity"></param>
        /// <param name="Token"></param>
        public udv_MobileSignIn SaveUser_Redis(UsersEntity Entity, UsersExtendEntity ExtendEntity, string Token)
        {
            var EntityRedis = new udv_MobileSignIn()
            {
                AliPayOpenID = ExtendEntity.AliPayID,
                AvatarUrl = ExtendEntity.AvatarAddress,
                Balance = Entity.Balance,
                Gold = Entity.GoldBean,
                IsCertification = ExtendEntity.IsVerify ?? false,
                IsRobot = Entity.IsRobot,
                Level = ExtendEntity.UserLevel,
                VIP = 0,
                SpecialGroup = ExtendEntity.SpecialLevel,
                Mobie = Entity.UserMobile,
                Nick = Entity.UserName,
                Pwd = Entity.UserPassword,
                PayPwd = Entity.PayPassword,
                QQOpenID = ExtendEntity.QQID,
                WechatOpenID = ExtendEntity.WechatID,
                Token = Token,
                UserCode = Entity.UserID == 0 ? ExtendEntity.UserID : Entity.UserID,
                FullName = ExtendEntity.FullName,
                IsCanLogin = Entity.IsCanLogin
            };
            new SystemRedis().SignInSessionRedis(EntityRedis);
            return EntityRedis;
        }

        /// <summary>
        /// 手机号码登陆
        /// </summary>
        /// <param name="Equipment"></param>
        /// <param name="SourceType"></param>
        /// <param name="Mobile"></param>
        /// <param name="Pwd"></param>
        /// <returns></returns>
        public LoginResult MobileSignIn(string Equipment, short SourceType, string Mobile, string Pwd)
        {
            LoginResult result = null;
            try
            {
                UsersEntity Users = null;
                UsersExtendEntity UsersExtend = null;
                LoginData userData = null;
                int RecCode = (int)ResultCode.Success;
                udv_MobileSignIn Entity = new SystemRedis().SignInByMobileRedis(Mobile);
                Pwd = EncryptAlgorithm.MD5(Pwd);
                if (Entity == null)
                {
                    Users = this.QueryEntityByUserMobile(Mobile);
                    if (Users == null)
                        RecCode = (int)ResultCode.UserNotExist;
                    else
                    {
                        #region Redis操作
                        UsersExtend = new UsersExtendBLL().QueryEntityByUserCode(Users.UserID);
                        if (UsersExtend == null)
                            UsersExtend = new UsersExtendEntity();
                        var TokenEntity = new BaseRedis().VerifyTokenRedis(string.Empty, Equipment);
                        new BaseRedis().GenerateUserTokenRedis(Equipment, TokenEntity.Token, Users.UserID);
                        Entity = this.SaveUser_Redis(Users, UsersExtend, TokenEntity.Token);
                        #endregion
                    }
                }
                else
                {
                    if (Entity.Pwd != Pwd)
                        RecCode = (int)ResultCode.LoginPwdError;
                    else
                    {
                        var EntityRedis = new BaseRedis().VerifyTokenRedis(Entity.Token);
                        if (EntityRedis == null)
                            EntityRedis = new BaseRedis().GenerateUserTokenRedis(Equipment, Entity.Token, Entity.UserCode);
                        //判断是否实名认证 实名认证是否有真实姓名
                        if (Entity.IsCertification && string.IsNullOrEmpty(Entity.FullName))
                            if (UsersExtend == null)
                            {
                                UsersExtend = new UsersExtendBLL().QueryEntityByUserCode(Entity.UserCode);
                                if (UsersExtend != null)
                                {
                                    Entity.FullName = UsersExtend.FullName;
                                    new SystemRedis().SignInSessionRedis(Entity);
                                }
                            }
                        if (!Entity.IsCanLogin)
                        {
                            var UserEntity_DB = new UsersBLL().QueryEntityByUserCode(Entity.UserCode);
                            if (UserEntity_DB != null)
                                Entity.IsCanLogin = UserEntity_DB.IsCanLogin;
                            new SystemRedis().SignInSessionRedis(Entity);
                        }
                    }
                }
                if (RecCode == (int)ResultCode.Success && Entity != null)
                {
                    if (Entity.IsCanLogin)
                    {
                        userData = new LoginData()
                        {
                            AvatarUrl = Entity.AvatarUrl,
                            Balance = Entity.Balance,
                            Gold = Entity.Gold,
                            IsCertification = Entity.IsCertification,
                            IsRobot = Entity.IsRobot,
                            Level = Entity.Level,
                            Mobie = Entity.Mobie,
                            Nick = Entity.Nick,
                            SpecialGroup = Entity.SpecialGroup,
                            Token = Entity.Token,
                            UserCode = Entity.UserCode,
                            VIP = 0,
                            FullName = Entity.FullName,
                            IsWithdrawPwd = string.IsNullOrEmpty(Entity.PayPwd) == true ? false : true,
                            Uid = DESEncrypt.Encrypt(Convert.ToString(Entity.UserCode))
                        };
                    }
                    else
                        RecCode = (int)ResultCode.UserIsCanLogin;
                }
                result = new LoginResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    Data = userData
                };
            }
            catch (Exception ex)
            {
                log.Write("手机号码登陆[MobileSignIn]：" + ex.StackTrace, true);
                result = new LoginResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 集成登录
        /// </summary>
        /// <param name="Equipment"></param>
        /// <param name="SourceType"></param>
        /// <param name="Code"></param>
        /// <param name="LoginType"></param>
        /// <returns></returns>
        public LoginResult IntegratedSignIn(string Equipment, short SourceType, string Code, short LoginType)
        {
            LoginResult result = null;
            try
            {
                udv_Integrated integrated = null;
                udv_MobileSignIn Entity = null;
                LoginData userData = null;
                int RecCode = (int)ResultCode.Success;
                if (LoginType == (int)LoginTypeEnum.QQ)
                    integrated = new Integrated.QQOAuth(Code).GetOpenID();
                else if (LoginType == (int)LoginTypeEnum.WeChat)
                {
                    integrated = new Integrated.WeChatOAuth(Code).Callback();
                }
                if (integrated == null || integrated.ErrCode != "0")
                    return new LoginResult()
                    {
                        Code = Convert.ToInt32(integrated.ErrCode),
                        Msg = integrated.ErrMsg
                    };
                if (LoginType == (int)LoginTypeEnum.QQ)
                {
                    Entity = new SystemRedis().SignInByQQTokenRedis(integrated.OpenId);
                    integrated.HeadImgUrl = new Integrated.QQOAuth().SaveImg(integrated.OpenId, integrated.HeadImgUrl);
                }
                else if (LoginType == (int)LoginTypeEnum.WeChat)
                {
                    this.WeChatCompatible(integrated.UnionId, integrated.OpenId); //微信openid与unionid兼容
                    integrated.OpenId = integrated.UnionId;  //微信使用unionid
                    Entity = new SystemRedis().SignInByWechatTokenRedis(integrated.OpenId);
                    integrated.HeadImgUrl = new Integrated.WeChatOAuth().SaveImg(integrated.OpenId, integrated.HeadImgUrl);
                }
                if (Entity == null)
                {
                    UsersExtendEntity UsersExtend = new UsersExtendBLL().QueryEntityByUserCode(LoginType, integrated.OpenId);
                    if (UsersExtend == null)
                    {
                        var Users = new UsersEntity()
                        {
                            IsCanLogin = true,
                            IsRobot = false,
                            UserName = integrated.NickName
                        };
                        long UserCode = this.InsertEntity(Users);
                        if (UserCode < 1)
                            RecCode = (int)ResultCode.RegisterFailure;
                        else
                        {
                            UsersExtend = new UsersExtendBLL().InsertIntegrated(UserCode, integrated.OpenId, integrated.Access_Token, LoginType, SourceType, integrated.NickName, integrated.HeadImgUrl);
                            if (UsersExtend == null)
                                RecCode = (int)ResultCode.RegisterFailure;
                            else
                            {
                                //注册送彩券
                                new CouponsBLL().RegisterGiveCoupons(UserCode);
                                //变更静态数据
                                new UsersBLL().Staticdata_AddUser(1);
                                var TokenEntity = new BaseRedis().VerifyTokenRedis(string.Empty, Equipment);
                                var TokenInfoEntity = new BaseRedis().GenerateUserTokenRedis(Equipment, TokenEntity.Token, UsersExtend.UserID);
                                Entity = SaveUser_Redis(Users, UsersExtend, TokenInfoEntity.Token);
                            }
                        }
                    }
                    else
                    {
                        var TokenEntity = new BaseRedis().VerifyTokenRedis(string.Empty, Equipment);
                        new BaseRedis().GenerateUserTokenRedis(Equipment, TokenEntity.Token, UsersExtend.UserID);
                        var Users = this.QueryEntityByUserCode(UsersExtend.UserID);
                        Entity = SaveUser_Redis(Users, UsersExtend, TokenEntity.Token);
                    }
                }
                if (!Entity.IsCanLogin)
                {
                    var UserEntity_DB = new UsersBLL().QueryEntityByUserCode(Entity.UserCode);
                    if (UserEntity_DB != null)
                        Entity.IsCanLogin = UserEntity_DB.IsCanLogin;
                }
                if (Entity.IsCanLogin)
                {
                    #region 更新头像
                    try
                    {
                        Entity.AvatarUrl = integrated.HeadImgUrl;
                        new SystemRedis().ModifySignInSessionRedis(Entity);
                        var UsersExtend = new UsersExtendBLL().QueryEntityByUserCode(LoginType, integrated.OpenId);
                        if (UsersExtend != null)
                        {
                            UsersExtend.AvatarAddress = integrated.HeadImgUrl;
                            new UsersExtendBLL().ModifyEntity(UsersExtend);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Write("集成登录DB更新头像错误：" + ex.Message, true);
                    }
                    #endregion
                    var entity = new BaseRedis().VerifyTokenRedis(Entity.Token);
                    if (entity == null)
                    {
                        var TokenEntity = new BaseRedis().VerifyTokenRedis(string.Empty, Equipment);
                        TokenEntity = new BaseRedis().GenerateUserTokenRedis(Equipment, TokenEntity.Token, Entity.UserCode);
                        Entity.Token = TokenEntity.Token;
                    }
                    //判断是否实名认证 实名认证是否有真实姓名
                    if (Entity.IsCertification && string.IsNullOrEmpty(Entity.FullName))
                    {
                        var UsersExtendEntity = new UsersExtendBLL().QueryEntityByUserCode(Entity.UserCode);
                        Entity.FullName = UsersExtendEntity.FullName;
                    }
                    userData = new LoginData()
                    {
                        AvatarUrl = Entity.AvatarUrl,
                        Balance = Entity.Balance,
                        Gold = Entity.Gold,
                        IsCertification = Entity.IsCertification,
                        IsRobot = Entity.IsRobot,
                        Level = Entity.Level,
                        Mobie = Entity.Mobie,
                        Nick = Entity.Nick,
                        SpecialGroup = Entity.SpecialGroup,
                        Token = Entity.Token,
                        UserCode = Entity.UserCode,
                        VIP = 0,
                        FullName = Entity.FullName,
                        IsWithdrawPwd = string.IsNullOrEmpty(Entity.PayPwd) == true ? false : true,
                        Uid = DESEncrypt.Encrypt(Convert.ToString(Entity.UserCode))
                    };
                    RecCode = (int)ResultCode.Success;
                }
                else
                    RecCode = (int)ResultCode.UserIsCanLogin;
                result = new LoginResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    Data = userData
                };
            }
            catch (Exception ex)
            {
                log.Write("集成登陆[IntegratedSignIn]：" + ex.StackTrace, true);
                result = new LoginResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 单点登录
        /// </summary>
        /// <param name="Equipment"></param>
        /// <param name="Token"></param>
        /// <param name="TimeStamp"></param>
        /// <returns></returns>
        public ApplyInitiateResult SSOSignIn(string Equipment, string Token)
        {
            ApplyInitiateResult result = null;
            try
            {
                bool IsVerifyToken = false;
                LoginData userData = null;
                int RecCode = (int)ResultCode.Success;
                string RecToken = Token;
                string SystemWinMoney = new SchemesWinBLL().SystemTotalWin();
                List<LotteryData> SystemLotteryData = new LotteriesBLL().SystemLottyData();
                List<ApplyAd> ActivityEntitys = new ActivityBLL().QueryEntitysAd();
                udv_TokenInfo SSOEntity = new BaseRedis().VerifyTokenRedis(Token, Equipment);
                if (SSOEntity.TokenType == 0)//游客
                    RecToken = SSOEntity.Token;
                else
                {
                    userData = this.SetUserData(SSOEntity.UserCode, Token);
                    if (userData != null)
                        IsVerifyToken = true;
                    else
                    {
                        RecToken = new BaseRedis().VerifyTokenRedis("0", Equipment).Token;
                        RecCode = (int)ResultCode.UserIsCanLogin;
                    }
                }
                result = new ApplyInitiateResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    IsVerifyToken = IsVerifyToken,
                    Token = RecToken,
                    LoginData = userData,
                    LotteryData = SystemLotteryData,
                    SystemTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
                    SystemTotalWin = SystemWinMoney,
                    ActivityData = ActivityEntitys
                };

            }
            catch (Exception ex)
            {
                log.Write("单点登录错误[SSOSignIn]：" + ex.StackTrace, true);
                result = new ApplyInitiateResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="UserCode"></param>
        /// <returns></returns>
        public OutLoginResult OutLogin(string Equipment, long UserCode)
        {
            OutLoginResult result = null;
            try
            {
                //造临时令牌
                var entity = new BaseRedis().VerifyTokenRedis("", Equipment);
                result = new OutLoginResult()
                {
                    Code = (int)ResultCode.Success,
                    Msg = Common.GetDescription(ResultCode.Success),
                    Token = entity.Token
                };
            }
            catch (Exception ex)
            {
                log.Write("退出登录错误[OutLogin]：" + ex.StackTrace, true);
                result = new OutLoginResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="Equipment">设备信息</param>
        /// <param name="Token">令牌</param>
        /// <param name="Mobile">手机号码</param>
        /// <param name="VerifyType">验证码类型</param>
        /// <returns></returns>
        public JsonResult SendVerifyCode(string Equipment, string Token, string Mobile, byte VerifyType)
        {
            JsonResult result = null;
            try
            {
                var red = new SystemRedis();
                int RecCode = (int)ResultCode.Success;
                if (red.IsSendVerifyCode(Mobile))
                {
                    string VeriftCode = new Random().Next(100000, 999999).ToString();
                    red.SendVerifyCodeRedis(Mobile, VeriftCode, VerifyType);
                    string SmsResult = SMS.SendSms(Mobile, VerifyType, VeriftCode);
                    if (!SmsResult.Contains(":0,"))
                        RecCode = (int)ResultCode.SendException;
                    else
                        red.RecordSendTime(Mobile, VeriftCode);
                }
                else
                {
                    RecCode = (int)ResultCode.SendVerifyCodeMoreTime;
                }

                result = new JsonResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode)
                };
            }
            catch (Exception ex)
            {
                log.Write("发送验证码错误[SendVerifyCode]：" + ex.StackTrace, true);
                result = new JsonResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 校验验证码
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="Mobile"></param>
        /// <param name="VerifyCode"></param>
        /// <param name="VerifyType"></param>
        /// <returns></returns>
        public JsonResult VerifyCode(string Mobile, string VerifyCode, byte VerifyType)
        {
            JsonResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                int VerifyResult = new SystemRedis().VerifyCodeRedis(Mobile, VerifyCode, VerifyType);
                if (VerifyResult != (int)ResultCode.Success)
                {
                    if (VerifyResult == 1)
                        RecCode = (int)ResultCode.CodeError;
                    else
                        RecCode = (int)ResultCode.CodeInvalidation;
                }
                result = new JsonResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode)
                };
            }
            catch (Exception ex)
            {
                log.Write("验证码校验错误[VerifyCode]：" + ex.StackTrace, true);
                result = new JsonResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 校验令牌
        /// </summary>
        /// <param name="Token"></param>
        /// <returns></returns>
        public JsonResult VerifyAuth(string Token)
        {
            JsonResult result = null;
            try
            {
                int RecCode = (int)ResultCode.TokenError;
                var entity = new BaseRedis().VerifyTokenRedis(Token);
                if (entity != null)
                {
                    if (entity.TokenType == 0)
                        RecCode = (int)ResultCode.Sightseer;
                    else
                        RecCode = (int)ResultCode.User;
                }
                result = new JsonResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode)
                };
            }
            catch (Exception ex)
            {
                log.Write("校验令牌错误：" + ex.StackTrace, true);
                result = new JsonResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 手机号码注册
        /// </summary>
        /// <param name="Equipment">设备信息</param>
        /// <param name="SourceType">终端 0PC 1Android 2IOS 3Ipad</param>
        /// <param name="Mobile">手机号码</param>
        /// <param name="Pwd">密码</param>
        /// <param name="VerifyCode">验证码</param>
        /// <returns></returns>
        public LoginResult MobileRegister(string Equipment, byte SourceType, string Mobile, string Pwd, string VerifyCode)
        {
            LoginResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                LoginData userData = null;
                int VerifyResult = new SystemRedis().VerifyCodeRedis(Mobile, VerifyCode, (int)VerifyTypeEnum.Register);
                if (VerifyResult == (int)ResultCode.Success) //验证码正确
                {
                    Pwd = EncryptAlgorithm.MD5(Pwd);
                    var usersEntity = this.QueryEntityByUserMobile(Mobile);
                    if (usersEntity != null)
                        RecCode = (int)ResultCode.Mobiles;
                    else
                    {
                        #region 注册到db
                        UsersEntity Entity = new UsersEntity()
                        {
                            UserPassword = Pwd,
                            UserMobile = Mobile,
                            UserName = Mobile
                        };
                        UsersExtendEntity ExtendEntity = new UsersExtendEntity()
                        {
                            BindType = 1,
                            IsBindTel = true,
                            NickName = Mobile,
                            SourceType = SourceType,
                        };
                        long UserCode = this.InsertEntity(Entity);
                        if (UserCode <= 0)
                            RecCode = (int)ResultCode.RegisterFailure;
                        else
                        {
                            // 注册送彩券
                            bool Coupons = new CouponsBLL().RegisterGiveCoupons(UserCode);
                            //变更静态数据
                            new UsersBLL().Staticdata_AddUser(1);
                            ExtendEntity.UserID = UserCode;
                            new UsersExtendBLL().InsertInfo(ExtendEntity);
                            #region 拼凑redis数据(用户登录信息)
                            var GenerateUser = new BaseRedis().VerifyTokenRedis(string.Empty, Equipment);
                            GenerateUser = new BaseRedis().GenerateUserTokenRedis(Equipment, GenerateUser.Token, UserCode);
                            SaveUser_Redis(Entity, ExtendEntity, GenerateUser.Token);
                            userData = new LoginData()
                            {
                                AvatarUrl = ExtendEntity.AvatarAddress,
                                Balance = Entity.Balance,
                                Gold = Entity.GoldBean,
                                IsCertification = ExtendEntity.IsVerify ?? false,
                                IsRobot = Entity.IsRobot,
                                Level = ExtendEntity.UserLevel,
                                Mobie = Entity.UserMobile,
                                Nick = ExtendEntity.NickName,
                                SpecialGroup = ExtendEntity.SpecialLevel,
                                Token = GenerateUser.Token,
                                UserCode = ExtendEntity.UserID,
                                VIP = 0,
                                FullName = ExtendEntity.FullName,
                                IsWithdrawPwd = string.IsNullOrEmpty(Entity.PayPassword) == true ? false : true,
                                CouponsCount = Coupons == true ? 1 : 0
                            };
                            #endregion
                            RecCode = (int)ResultCode.Success;
                        }
                        #endregion
                    }
                }
                else if (VerifyResult == 1)
                    RecCode = (int)ResultCode.CodeError;
                else
                    RecCode = (int)ResultCode.CodeInvalidation;
                result = new LoginResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    Data = userData
                };
            }
            catch (Exception ex)
            {
                log.Write("手机号码注册错误[MobileRegister]：" + ex.StackTrace, true);
                result = new LoginResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }


        /// <summary>
        /// 重置密码(找回密码)
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="Mobile"></param>
        /// <param name="Pwd"></param>
        /// <param name="VerifyCode"></param>
        /// <returns></returns>
        public JsonResult ResetSignInPwd(string Mobile, string Pwd, string VerifyCode)
        {
            JsonResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                int VerifyResult = new SystemRedis().VerifyCodeRedis(Mobile, VerifyCode, (int)VerifyTypeEnum.RetrievePwd);
                if (VerifyResult == (int)ResultCode.Success)
                {
                    Pwd = EncryptAlgorithm.MD5(Pwd);
                    var SystemEntity = new SystemRedis().SignInByMobileRedis(Mobile);
                    if (SystemEntity != null)
                    {
                        SystemEntity.Pwd = Pwd;
                        var usersEntity = this.QueryEntityByUserCode(SystemEntity.UserCode);
                        usersEntity.UserPassword = Pwd;
                        this.ModifyEntity(usersEntity);
                        new SystemRedis().ModifySignInSessionRedis(SystemEntity);
                        RecCode = (int)ResultCode.Success;
                    }
                    else
                    {
                        var usersEntity = this.QueryEntityByUserMobile(Mobile);
                        if (usersEntity == null)
                            RecCode = (int)ResultCode.OldMobileFailure;
                        else
                        {
                            RecCode = (int)ResultCode.Success;
                            usersEntity.UserPassword = Pwd;
                            this.ModifyEntity(usersEntity);
                        }
                    }
                }
                else if (VerifyResult == 1)
                    RecCode = (int)ResultCode.CodeError;
                else
                    RecCode = (int)ResultCode.CodeInvalidation;
                result = new JsonResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode)
                };
            }
            catch (Exception ex)
            {
                log.Write("找回密码[ResetSignInPwd]：" + ex.StackTrace, true);
                result = new JsonResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 重置密码(登录密码 支付密码)
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="UserCode"></param>
        /// <param name="PwdType"></param>
        /// <param name="Pwd"></param>
        /// <param name="VerifyCode"></param>
        /// <returns></returns>
        public JsonResult ResetPwd(long UserCode, byte PwdType, string Pwd, string VerifyCode)
        {
            JsonResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                Pwd = EncryptAlgorithm.MD5(Pwd);
                var SignInEntity = new SystemRedis().SignInByUserCodeRedis(UserCode);
                byte VerifyType = (int)VerifyTypeEnum.UpdateLoginPwd;
                if (PwdType == 2)
                    VerifyType = (int)VerifyTypeEnum.UpdatePaymentPwd;
                int VerifyResult = new SystemRedis().VerifyCodeRedis(SignInEntity.Mobie, VerifyCode, VerifyType);
                if (VerifyResult == 0)
                {
                    var UsersEntity = this.QueryEntityByUserCode(UserCode);
                    if (PwdType == 1)
                    {
                        UsersEntity.UserPassword = Pwd;
                        SignInEntity.Pwd = Pwd;
                    }
                    else
                    {
                        UsersEntity.PayPassword = Pwd;
                        SignInEntity.PayPwd = Pwd;
                    }
                    RecCode = (int)ResultCode.Success;
                    this.ModifyEntity(UsersEntity);
                    new SystemRedis().ModifySignInSessionRedis(SignInEntity);
                }
                else if (VerifyResult == 1)
                    RecCode = (int)ResultCode.CodeError;
                else
                    RecCode = (int)ResultCode.CodeInvalidation;
                result = new JsonResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode)
                };
            }
            catch (Exception ex)
            {
                log.Write("重置密码错误[ResetPwd]：" + ex.StackTrace, true);
                result = new JsonResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 修改昵称
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="UserCode"></param>
        /// <param name="Nick"></param>
        /// <returns></returns>
        public JsonResult ChangeNick(long UserCode, string Nick)
        {
            JsonResult result = null;
            try
            {
                var UsersEntity = this.QueryEntityByUserCode(UserCode);
                var SignInEntity = new SystemRedis().SignInByUserCodeRedis(UserCode);
                var ExtendEntity = new UsersExtendBLL().QueryEntityByUserCode(UserCode);
                SignInEntity.Nick = Nick;
                UsersEntity.UserName = Nick;
                ExtendEntity.NickName = Nick;
                this.ModifyEntity(UsersEntity);
                new UsersExtendBLL().ModifyEntity(ExtendEntity);
                new SystemRedis().ModifySignInSessionRedis(SignInEntity);
                result = new JsonResult()
                {
                    Code = (int)ResultCode.Success,
                    Msg = Common.GetDescription(ResultCode.Success)
                };
            }
            catch (Exception ex)
            {
                log.Write("修改昵称错误[ChangeNick]：" + ex.StackTrace, true);
                result = new JsonResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 修改手机号码
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="UserCode"></param>
        /// <param name="Mobile"></param>
        /// <param name="VerifyCode"></param>
        /// <returns></returns>
        public JsonResult ChangeMobile(long UserCode, string Mobile, string VerifyCode)
        {
            JsonResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                int VerifyResult = new SystemRedis().VerifyCodeRedis(Mobile, VerifyCode, (int)VerifyTypeEnum.UpdateMobile);
                if (VerifyResult == (int)ResultCode.Success)
                {
                    var SignInEntity = new SystemRedis().SignInByMobileRedis(Mobile);
                    if (SignInEntity == null || SignInEntity.UserCode == UserCode)
                    {
                        var UsersEntity = this.QueryEntityByUserMobile(Mobile);
                        if (UsersEntity == null || UsersEntity.UserID == UserCode)
                        {
                            UsersEntity = this.QueryEntityByUserCode(UserCode);
                            SignInEntity = new SystemRedis().SignInByUserCodeRedis(UserCode);
                            UsersEntity.UserMobile = Mobile;
                            SignInEntity.Mobie = Mobile;
                            this.ModifyEntity(UsersEntity);
                            new SystemRedis().ModifySignInSessionRedis(SignInEntity);
                            RecCode = (int)ResultCode.Success;
                        }
                        else
                            RecCode = (int)ResultCode.Mobiles;
                    }
                    else
                        RecCode = (int)ResultCode.Mobiles;
                }
                else if (VerifyResult == 1)
                    RecCode = (int)ResultCode.CodeError;
                else
                    RecCode = (int)ResultCode.CodeInvalidation;
                result = new JsonResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode)
                };

            }
            catch (Exception ex)
            {
                log.Write("修改手机号码错误[ChangeMobile]：" + ex.StackTrace, true);
                result = new JsonResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }
        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="UserCode"></param>
        /// <returns></returns>
        public LoginResult QueryUserInfo(string Token, long UserCode)
        {
            LoginResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                LoginData userData = null;
                var UserInfoEntity = new SystemRedis().SignInByUserCodeRedis(UserCode);
                if (UserInfoEntity == null)
                    RecCode = (int)ResultCode.NullData;
                else
                {
                    var UserEntity = new UsersBLL().QueryEntityByUserCode(UserCode);
                    if (UserEntity == null)
                        RecCode = (int)ResultCode.NullData;
                    else
                    {
                        if (UserEntity.Balance != UserInfoEntity.Balance || UserInfoEntity.Gold != UserEntity.GoldBean)
                        {
                            UserInfoEntity.Balance = UserEntity.Balance;
                            UserInfoEntity.Gold = UserEntity.GoldBean;
                            new SystemRedis().SignInSessionRedis(UserInfoEntity);
                        }
                        int RecCount = 0;
                        new CouponsBLL().QueryCoupons(UserCode, true, 1, 11, ref RecCount);
                        RecCode = (int)ResultCode.Success;
                        userData = new LoginData()
                        {
                            AvatarUrl = UserInfoEntity.AvatarUrl,
                            Balance = UserInfoEntity.Balance,
                            FullName = UserInfoEntity.FullName,
                            Gold = UserInfoEntity.Gold,
                            IsCertification = UserInfoEntity.IsCertification,
                            IsRobot = UserInfoEntity.IsRobot,
                            Level = UserInfoEntity.Level,
                            Mobie = UserInfoEntity.Mobie,
                            Nick = UserInfoEntity.Nick,
                            SpecialGroup = UserInfoEntity.SpecialGroup,
                            Token = Token,
                            UserCode = UserInfoEntity.UserCode,
                            VIP = UserInfoEntity.VIP,
                            IsWithdrawPwd = string.IsNullOrEmpty(UserEntity.PayPassword) == true ? false : true,
                            CouponsCount = RecCount
                        };
                    }
                }
                result = new LoginResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    Data = RecCode != (int)ResultCode.Success ? null : userData
                };
            }
            catch (Exception ex)
            {
                result = new LoginResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy),
                    Data = null
                };
                log.Write("查询Redis用户信息[QueryUserInfo]：" + ex.StackTrace, true);
            }
            return result;
        }
        /// <summary>
        /// 查询用户余额
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="UserCode"></param>
        /// <returns></returns>
        public UserBalanceResult QueryUserBalance(string Token, long UserCode)
        {
            UserBalanceResult result = null;
            try
            {
                long RecBalance = 0;
                long RecGold = 0;
                int RecCode = (int)ResultCode.Success;
                var UserInfoEntity = new SystemRedis().SignInByUserCodeRedis(UserCode);
                if (UserInfoEntity == null)
                    RecCode = (int)ResultCode.NullData;
                else
                {
                    var UserEntity = new UsersBLL().QueryEntityByUserCode(UserCode);
                    if (UserEntity == null)
                        RecCode = (int)ResultCode.NullData;
                    else
                    {
                        if (UserEntity.Balance != UserInfoEntity.Balance || UserEntity.GoldBean != UserInfoEntity.Gold)
                        {
                            UserInfoEntity.Balance = UserEntity.Balance;
                            UserInfoEntity.Gold = UserEntity.GoldBean;
                            new SystemRedis().SignInSessionRedis(UserInfoEntity);
                        }
                        RecCode = (int)ResultCode.Success;
                        RecBalance = UserInfoEntity.Balance;
                        RecGold = UserInfoEntity.Gold;
                    }
                }
                result = new UserBalanceResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    Balance = RecBalance,
                    Gold = RecGold
                };
            }
            catch (Exception ex)
            {
                result = new UserBalanceResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
                log.Write("查询Redis用户余额[QueryUserBalance]：" + ex.StackTrace, true);
            }
            return result;
        }
        /// <summary>
        /// 验证手机号码是否被注册
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="Mobile"></param>
        /// <returns></returns>
        public JsonResult VerifyMobile(string Mobile)
        {
            JsonResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                var UserEntity = this.QueryEntityByUserMobile(Mobile);
                if (UserEntity != null)
                    RecCode = (int)ResultCode.Mobiles;
                result = new JsonResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode)
                };
            }
            catch (Exception ex)
            {
                log.Write("验证手机号码是否被注册错误[VerifyMobile]：" + ex.StackTrace, true);
            }
            return result;
        }
        /// <summary>
        /// 微信分享注册
        /// </summary>
        /// <param name="Uid"></param>
        /// <param name="UnionId"></param>
        /// <param name="SourceType"></param>
        /// <param name="NickName"></param>
        /// <param name="HeadImgUrl"></param>
        /// <returns></returns>
        public JsonResult ActivtiyRegister_WX(long Uid, string UnionId, short SourceType, string NickName, string HeadImgUrl)
        {
            JsonResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                long UAmount = 100;
                if (string.IsNullOrEmpty(NickName))
                {
                    NickName = string.Format("微信注册{0}", new Random().Next(1, 9999));
                }
                long.TryParse(ConfigHelper.GetConfigString("KEYUAMOUNT"), out UAmount);
                var UsersExtendEntity = new UsersExtendBLL().QueryEntityByUserCode(2, UnionId);
                if (UsersExtendEntity == null)
                {
                    UsersEntity UsersEntity = new UsersEntity()
                    {
                        UserName = NickName
                    };
                    long UserCode = new UsersBLL().InsertEntity(UsersEntity);
                    if (UserCode < 1)
                    {
                        RecCode = (int)ResultCode.RegisterFailure;
                        log.Write("微信分享注册失败(UsersEntity).");
                    }
                    else
                    {
                        UsersExtendEntity = new UsersExtendBLL().InsertIntegrated(UserCode, UnionId, string.Empty, 2, SourceType, NickName, HeadImgUrl, Uid.ToString());
                        if (UsersExtendEntity == null)
                        {
                            RecCode = (int)ResultCode.RegisterFailure;
                            log.Write("微信分享注册失败(UsersExtendEntity).");
                        }
                        else
                        {
                            Task.Factory.StartNew(() =>
                            {
                                //注册人送彩券
                                new CouponsBLL().RegisterGiveCoupons(UserCode);

                                int SharingCount = 3;
                                int DaySharingCount = 0;
                                DateTime dt = DateTime.Now;
                                int.TryParse(System.Configuration.ConfigurationManager.AppSettings["Sharing"], out SharingCount);
                                var udv_Sharing = new UserRedis().QueryUserSharing(Uid);
                                if (udv_Sharing == null)
                                {
                                    udv_Sharing = new CL.View.Entity.Other.udv_Sharing();
                                    udv_Sharing.Sharing = 1;
                                    udv_Sharing.Time = dt;
                                    udv_Sharing.UserCode = Uid;
                                }
                                else
                                {
                                    if (udv_Sharing.Time.ToString("yyyyMMdd") == dt.ToString("yyyyMMdd"))
                                    {
                                        DaySharingCount = udv_Sharing.Sharing;
                                        udv_Sharing.Sharing = udv_Sharing.Sharing + 1;
                                    }
                                    else
                                    {
                                        DaySharingCount = 1;
                                        udv_Sharing.Sharing = 1;
                                        udv_Sharing.Time = dt;
                                    }
                                }
                                new UserRedis().SaveUserSharing(udv_Sharing);
                                if (DaySharingCount <= SharingCount)
                                {
                                    //推荐人送彩券 推荐人每天分享佣金有限制
                                    new CouponsBLL().RegisterGiveCoupons(Uid, UAmount);
                                }
                            });
                            RecCode = (int)ResultCode.Success;
                        }
                    }
                }
                result = new JsonResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode)
                };
            }
            catch (Exception ex)
            {
                log.Write("微信分享注册失败：" + ex.StackTrace, true);
                result = new JsonResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }
        /// <summary>
        /// 兑换彩豆
        /// </summary>
        /// <param name="UserCode"></param>
        /// <param name="Amount"></param>
        /// <param name="Gold"></param>
        /// <returns></returns>
        public UserBalanceResult ExchangeBean(long UserCode, long Amount, long Gold)
        {
            int RecCode = (int)ResultCode.Success;
            long Balance = 0;
            long GoldBean = 0;
            try
            {
                int Rec = ExchangeCaileBean(UserCode, Amount, Gold, ref Balance, ref GoldBean);
                if (Rec != 0)
                {
                    if (Rec == -1)
                        RecCode = (int)ResultCode.WaitPayment;
                    else
                        RecCode = Rec;
                }
            }
            catch (Exception ex)
            {
                log.Write(string.Format("兑换彩豆错误：{0}", ex.StackTrace), true);
                RecCode = (int)ResultCode.WaitPayment;
            }
            return new UserBalanceResult()
            {
                Code = RecCode,
                Msg = Common.GetDescription((ResultCode)RecCode),
                Balance = Balance,
                Gold = GoldBean
            };
        }
        #endregion

        #region 撤单发短信
        /// <summary>
        /// 撤单发短信和极光推送
        /// </summary>
        /// <param name="SchemeID"></param>
        /// <param name="WinMoney"></param>
        /// <returns></returns>
        public bool SendWinMoneyContent(long SchemeID, string IsuseName, long Money)
        {
            try
            {
                Money = Money / 100;
                var SchemeEntity = new SchemesBLL().QueryEntity(SchemeID);
                var UserEntity = new SystemRedis().SignInByUserCodeRedis(SchemeEntity.InitiateUserID);
                string TemplateStr = new TemplateConfigBLL().QueryRevokePushTemplate();
                if (string.IsNullOrEmpty(TemplateStr))
                    return false;
                //亲爱的{0}会员，你购买的{1}第{2}期订单[单号：{3}]撤单，撤单金额为{4}元
                TemplateStr = string.Format(TemplateStr, UserEntity.Nick, Common.GetDescription((LotteryInfo)SchemeEntity.LotteryCode), IsuseName, SchemeEntity.SchemeNumber, Money);
                #region 发短信
                try
                {
                    if (!string.IsNullOrEmpty(UserEntity.Mobie))
                        SMS.SendModel(UserEntity.Mobie, TemplateStr);
                }
                catch (Exception ex)
                {
                    new Log("Push").Write("撤单短信推送错误：" + ex.Message, true);
                }
                #endregion
                #region 发推送
                try
                {
                    //百度推送
                    new UsersPushBLL().PushMessager_Android_Single(UserEntity.UserCode, "系统撤单", TemplateStr, string.Empty);
                }
                catch (Exception ex)
                {
                    new Log("Push").Write("撤单环信推送错误：" + ex.Message, true);
                }
                #endregion
                return true;
            }
            catch (Exception ex)
            {
                new Log("Push").Write("撤单推送错误：" + ex.Message, true);
                return false;
            }
        }
        #endregion
    }
}
